<script lang="ts" setup>
import type { AddType, DeleteType, UpdataType } from './types';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { isEmpty } from '@vben/utils';
import { $t } from '@vben/locales';
import { Button, MenuItem, message, Modal, Switch } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteAdminRoles,
  getAdminRoles,
  getAdminRolesApiAuthorize,
  getAdminRolesAuthorize,
  putAdminRoles,
} from '#/api/admin/roles';
import { postSwaggerImportApi } from '#/api/system';
import ButtonAction from '#/components/ButtonAction';
import Icon from '#/components/Icons';
import { useAuthStore } from '#/store';
import {
  handleGroupToTree,
  handleTree,
  sortByField,
  toggleStatus,
} from '#/utils';

import { FormModalView, TableModalView } from './components';

defineOptions({
  name: 'AdminRbac',
});
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');

const gridOptions: VxeGridProps<UpdataType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  columns: [
    { title: '序号', type: 'seq', width: 50 },
    { field: 'name', title: $t('page.common.Name') },
    { field: 'type', title: $t('page.common.Category') },
    { field: 'remark', title: $t('admin.Remark') },
    { field: 'status', title: $t('page.common.Status'), slots: { default: 'status' } },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t('page.common.Action'),
      width: 240,
    },
  ],
  pagerConfig: {
    enabled: false,
  },
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const { data } = await getAdminRoles();
        data.list = sortByField(data.list, 'list_order');
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const handleDelete = async (row: DeleteType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteAdminRoles(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

const onChange = async (row: UpdataType) => {
  Modal.confirm({
    title: $t('admin.systemMessage'),
    content: $t('admin.confirmTo')+`${row.status === 0 ? $t('admin.Disable') : $t('admin.Enable')}?`,
    async onOk() {
      try {
        await putAdminRoles(row.id, row);
        message.success(`${row.status === 0 ? $t('admin.Disable') : $t('admin.Enable')}`);
      } catch {
        row.status = toggleStatus(row.status);
      }
    },
    onCancel() {
      row.status = toggleStatus(row.status);
    },
  });
};

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const [TableModal, tableModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: TableModalView,
});
const openDialog = async (title: 'Add' | 'Edit', row?: AddType | null) => {
  formModalApi.setState({
    title: $t('page.common.'+title)+` ${viewTitle}`,
  });
  formModalApi.setData(row);
  formModalApi.open();
};

const openDataDialog = async (
  title: 'apiPermission' | 'menuPermission',
  row?: null | UpdataType,
) => {
  if (!row) return;

  if (title === 'menuPermission') {
    // 菜单权限逻辑
    tableModalApi.setState({
      title: `${row.name}-`+$t('admin.'+title)+$t('admin.manage'),
    });

    const {
      data: { list },
    } = await getAdminRolesAuthorize(row.id);

    const newArr = Object.values(list)
      .filter(
        (value: any) =>
          typeof value === 'object' && value !== null && value.status === 1,
      )
      .map((value: any) => ({ ...value }));
    const menusTree = handleTree(
      sortByField(newArr, 'list_order'),
      'id',
      'parent_id',
    );

    const checkedIds = newArr
      .filter((obj) => obj.checked === 1)
      .map((item) => ({ value: item.id, label: item.name }));

    tableModalApi.setData({
      checkedIds,
      menusTree,
      id: row.id,
      type: 'menus',
    });

    tableModalApi.open();
  } else if (title === 'apiPermission') {
    // 接口权限逻辑
    tableModalApi.setState({
      title: `${row.name}-`+$t('admin.'+title)+` `+$t('admin.manage'),
    });
    const { data } = await getAdminRolesApiAuthorize(row.id);
    if (isEmpty(data.list)) {
      Modal.confirm({
        title: $t('admin.systemMessage'),
        content: $t('admin.apiMenuNotInitialized'),
        async onOk() {
          await postSwaggerImportApi();
          message.success($t('admin.initSuccess'));
        },
      });
    } else {
      const list = data.list;
      const menusTree = handleGroupToTree(list);

      const checkedIds = list
        .filter((obj: any) => obj.checked === 1)
        .map((item: any) => ({ value: item.id, label: item.name }));
      tableModalApi.setData({
        checkedIds,
        menusTree,
        id: row.id,
        type: 'api',
      });

      tableModalApi.open();
    }
  }
};
</script>

<template>
  <Page auto-content-height>
    <FormModal />
    <TableModal />
    <Grid :table-title="`${viewTitle} `+$t('page.common.List')">
      <template #toolbar-tools>
        <Button
          :disabled="!useAuthStore().hasAccessByRoles(['super'])"
          class="mr-2"
          type="primary"
          @click="openDialog('Add')"
        >
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t('page.common.Add')}} {{ viewTitle }}
        </Button>
      </template>
      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :disabled="!useAuthStore().hasAccessByRoles(['super'])"
          :un-checked-value="0"
          :checked-children="$t('admin.Enable')"
          :un-checked-children="$t('admin.Disable')"
          @change="onChange(row)"
        />
      </template>

      <template #action="{ row }">
        <ButtonAction
          :disabled="!useAuthStore().hasAccessByRoles(['super'])"
          :row="row"
          :show-data-management="true"
          @delete="handleDelete(row)"
          @edit="openDialog('Edit', row)"
        >
          <template #menuContent>
            <MenuItem>
              <Button
                :disabled="!useAuthStore().hasAccessByRoles(['super'])"
                type="link"
                @click="openDataDialog('menuPermission', row)"
              >
                <template #icon>
                  <span class="anticon">
                    <Icon icon="ri:add-line" />
                  </span>
                </template>
                {{$t('admin.menuPermission')}}
              </Button>
            </MenuItem>
            <MenuItem>
              <Button
                :disabled="!useAuthStore().hasAccessByRoles(['super'])"
                type="link"
                @click="openDataDialog('apiPermission', row)"
              >
                <template #icon>
                  <span class="anticon">
                    <Icon icon="ri:add-line" />
                  </span>
                </template>
                {{$t('admin.apiPermission')}}
              </Button>
            </MenuItem>
          </template>
        </ButtonAction>
      </template>
    </Grid>
  </Page>
</template>
